package com.intelligentmeterreadingsys.otherequipment.activity;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.android.rfid.RfidHelper;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.intelligentmeterreadingsys.R;
import com.intelligentmeterreadingsys.otherequipment.db.EquipementDao;
import com.intelligentmeterreadingsys.povo.OtherEquipmentPOVO;
import com.intelligentmeterreadingsys.povo.TypePoVo;
import com.intelligentmeterreadingsys.util.BaiDuGpsUtil;
import com.intelligentmeterreadingsys.util.BluetoothHelp;
import com.intelligentmeterreadingsys.util.DateUtil;
import com.intelligentmeterreadingsys.util.SharedPreferenceUtil;
import com.intelligentmeterreadingsys.util.TipHelper;

import dbhelper.DbTableName;
import dbhelper.XmlNameHelper;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

/**
 * 设备更换
 * 
 * @author king
 * 
 */
public class EquipementReplaceActivity extends Activity implements
		OnClickListener,BDLocationListener {
	public TextView textview1;// 经度
	public TextView textview2;// 维度
	public TextView textview3;// 旧设备编号
	public TextView textview4;// Rfid编号
	public EditText edit1;// 新设备编号
	public EditText edit2;// 安装地址
	public EditText edit3;// 设备描述
	public EditText edit4;// 精确地址
	public EditText edit5;// 更换原因
	public Spinner spinner;// 设备类型
	public Button button1;// 读卡
	public Button button2;// 定位
	public Button button3;// 保存
	public Button button4;// 上传

	public String type;// 类型名称
	public String typeid = "0";
	public Double Latitude;// 维度
	public Double Longitude;// 经度
	public List<TypePoVo> list;// 类型集合
	public String[] date = null;
	public ArrayList<String> imagepath;
	private final static int DIALOG = 1;
	private static final int REQUEST_CODE_TAKE_IMAGE = 1;
	public String locationtype = "gps";
	public static final int ITEM0 = Menu.FIRST;// 系统值
	public LocationClient client;
	public long time;
	public ProgressDialog pd;
	public OtherEquipmentPOVO oldereq=null;
	public OtherEquipmentPOVO eq = null;
	public String id = "0";
	public boolean ismodify = false;
	public String RfidNumber = "";
	public String xieyi = "15693";
	public RfidHelper rh;// 读卡帮助对象
	public String readtype = "终端读卡";
    public SharedPreferenceUtil sp;
	public BluetoothHelp bluehelp;
	public String[] readdate;
	public boolean isbluetooth = true;
	public boolean isStop = false;
	public boolean isSave = false;
	public String url = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.other_equipment_replace);
		id=getIntent().getStringExtra("equipementId");
		sp=new SharedPreferenceUtil(this);
		init();

	}

	// 初始化控件
	public void init() {
		textview1 = (TextView) findViewById(R.id.other_equipment_replace_longitude);
		textview2 = (TextView) findViewById(R.id.other_equipment_replace_latitude);
		textview3 = (TextView) findViewById(R.id.other_equipment_replace_ordernumber);
		textview4 = (TextView) findViewById(R.id.other_equipment_replace_rfidnumber);
		edit1 = (EditText) findViewById(R.id.other_equipment_replace_newnumber);
		edit2 = (EditText) findViewById(R.id.other_equipment_replace_adds);
		edit3 = (EditText) findViewById(R.id.other_equipment_replace_desc);
		edit4 = (EditText) findViewById(R.id.other_equipment_replace_locationadds);
		edit5 = (EditText) findViewById(R.id.other_equipment_replace_reason);
		button1 = (Button) findViewById(R.id.other_equipment_replace_readcard);
		button2 = (Button) findViewById(R.id.other_equipment_replace_latitude);
		button3 = (Button) findViewById(R.id.other_equipment_replace_save);
		button4 = (Button) findViewById(R.id.other_equipment_replace_upload);
		spinner = (Spinner) findViewById(R.id.other_equipment_replace_type);
		button1.setOnClickListener(this);
		button2.setOnClickListener(this);
		button3.setOnClickListener(this);
		button4.setOnClickListener(this);
		bluehelp=new BluetoothHelp(this);
		bluehelp.init();
		spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {

				type = arg0.getItemAtPosition(arg2).toString();
				if (arg2 != 0) {
					typeid = list.get(arg2 - 1).getNumber();					
				}

			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				type = "无";
				typeid = "0";

			}

		});
		EquipementDao dao = new EquipementDao(this);

		list = dao.queryOrderType();
		oldereq=dao.queryOne(id, null);
		if (ismodify) {
			getTypePosition(type);
		}

		if (list != null && list.size() > 0) {
			date = new String[list.size() + 1];
			if (!ismodify) {
				date[0] = "请选择";
			}
			for (int i = 0; i < list.size(); i++) {
				date[i + 1] = list.get(i).getName();
			}
		} else {

			date = new String[] { "请选择" };
		}
		dao.close();
		ArrayAdapter<String> ada = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, date);// 放数据
		ada.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(ada);
		date = new String[] { "gps", "netowrke" };
		client = new LocationClient(this);
		client.registerLocationListener(this);
		initlocation();
		initRFID(2);
		viewdate(oldereq);
		getTypePosition(oldereq.getTypename());
		
	}

	/**
	 * 定位初始化
	 */
	public void initlocation() {

		LocationClientOption option = BaiDuGpsUtil
				.getLocationClientOption(locationtype);
		client.setLocOption(option);

	}

	@Override
	public void onClick(View v) {
        switch (v.getId()) {
		case R.id.other_equipment_replace_readcard:
			pd = new ProgressDialog(this);
			pd.setMessage("扫描中.....");
			pd.show();
			RfidNumber = "";
			if (!readtype.equals("终端读卡")) {
				bluehelp.start();
				pd.dismiss();
			}
			isStop = true;
			new Thread(){

				@Override
				public void run() {
					while (isStop) {
						Date d = new Date();
						if (d.getTime() - time > 20000) {
							isStop = false;
							Message msg = MyHandler.obtainMessage();
							msg.what = 2;
							MyHandler.sendMessage(msg);
						}

						String id = "";
						if (readtype.equals("终端读卡")) {
							id = rh.readIDString();
						} else {

							id = bluehelp.getRfidId();
						}
						if (!TextUtils.isEmpty(id)) {
							isStop = false;
							Message msg = MyHandler.obtainMessage();
							msg.what = 1;
							msg.obj = id;
							MyHandler.sendMessage(msg);
						}
						try {
							Thread.sleep(200);
						} catch (InterruptedException e) {

							e.printStackTrace();
						}
					}
					super.run();
				}
				
			};
			break;
		case R.id.other_equipment_replace_latitude:
			    boolean b=openGPSSettings();
			    if(b){
			    	initlocation();
					pd = new ProgressDialog(this);
					
					pd.setMessage("定位中...");
					pd.show();
					time = System.currentTimeMillis();
					
					client.start();
			    }
			break;
		case R.id.other_equipment_replace_save:
			if(TextUtils.isEmpty(edit1.getEditableText().toString())){
				Toast.makeText(this, "编号不能为空", Toast.LENGTH_SHORT).show();
				return;
			}
			if(typeid.equals("0")){
				Toast.makeText(this, "还没选择类型", Toast.LENGTH_SHORT).show();
				return;
			}
			showDialog(DIALOG);
			break;
		case R.id.other_equipment_replace_upload:
			
			break;
		default:
			break;
		}
	}

	@Override
	public void onReceiveLocation(BDLocation location) {
		getlocation(location);
		
	}

	@Override
	public void onReceivePoi(BDLocation arg0) {
		// TODO Auto-generated method stub
		
	}
	/**
	 * 判断GPS是否存在或开启
	 */
	public boolean openGPSSettings() {
		LocationManager alm = (LocationManager) getSystemService(this.LOCATION_SERVICE);

		if (alm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {

			return true;
		}
		Toast.makeText(this, "请开启GPS！", Toast.LENGTH_SHORT).show();
		Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS);
		startActivityForResult(intent, 0); // 此为设置完成后返回到获取界面
		return false;
	}

	/**
	 * 定位
	 * 
	 * @param location
	 */
	public void getlocation(BDLocation location) {
		
		if (location == null) {
			return;
		}

		if (locationtype.equals("gps") && location.getLocType() == 61) {
			textview1.setText("纬度:" + location.getLatitude());
			textview2.setText("经度:" + location.getLongitude());
			this.Latitude = location.getLatitude();
			this.Longitude = location.getLongitude();
			sp.insertValue(XmlNameHelper.GPSLATITUDE, location.getLatitude()+"");
			sp.insertValue(XmlNameHelper.GPSLONGITUDE, location.getLongitude()+"");
			sp.insertValue(XmlNameHelper.GPSDATE, System.currentTimeMillis()+"");
			Toast.makeText(EquipementReplaceActivity.this, "定位成功",
					Toast.LENGTH_SHORT).show();
			client.stop();
			pd.dismiss();
		} else{
			 Dialog dialog=null;
				String message="";
		         if(sp.getValue(XmlNameHelper.GPSDATE).equals("0")){
		        	 message="还没有定位成功过！";
		         }else{
		        	 long ti=System.currentTimeMillis()-Long.parseLong(sp.getValue(XmlNameHelper.GPSDATE));
		        	 System.out.println(ti+"--------");
		        	 message="最近一次定位时间在:"+DateUtil.getMuntion(ti);
		         }
		        
			 Builder builder=new android.app.AlertDialog.Builder(this);
	         //设置对话框的图标
	         builder.setIcon(R.drawable.buttondraw);	         
	         //设置对话框的标题
	       
	         builder.setMessage(message);
	        
         //添加一个确定按钮
	         builder.setPositiveButton(" 确 定 ", new DialogInterface.OnClickListener(){
	             public void onClick(DialogInterface dialog, int which) {
	            	 textview2.setText("纬度:" + sp.getValue(XmlNameHelper.GPSLATITUDE));
	     			textview1.setText("经度：" + sp.getValue(XmlNameHelper.GPSLONGITUDE));
	     			Latitude =Double.parseDouble(sp.getValue(XmlNameHelper.GPSLATITUDE));
	     			Longitude =Double.parseDouble(sp.getValue(XmlNameHelper.GPSLONGITUDE));
	     			dialog.dismiss();
	             }
	         });
	         builder.setNeutralButton("取消", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					textview2.setText("纬度:" + 0.0);
					textview1.setText("经度：" + 0.0);
					Longitude = 0.0;
					Latitude = 0.0;
					dialog.dismiss();
				}
			});
	         //创建一个单选按钮对话框
	         dialog=builder.create();
	         dialog.show();

		}

	}
	
	@Override
	protected void onDestroy() {
		if (client != null && client.isStarted()) {
			client.stop();
		}
		if(bluehelp!=null){
			bluehelp.stop();
		}
	
		super.onDestroy();
	}

	/**
	 * 修改时交换类型位置
	 * 
	 * @param type
	 * @return
	 */
	public int getTypePosition(String type) {
		if (list != null && list.size() > 0) {
			for (int k = 0; k < list.size(); k++) {
				if (list.get(k).getName().equals(type)) {
					spinner.setSelection(k + 1, true);
					return k;
				}
			}
		}
		return 0;

	};

	/**
	 * 初始化读卡
	 */
	public void initRFID(int type) {
		rh = RfidHelper.getInstance();
		rh.setCardType(type);
		rh.open();
		rh.setAllNoOfTimes(1);
		rh.setTimeInterval(50);
		// 设置激活读卡器后等待的时间.sdk默认10
		rh.setPingTimeInterval(10);
	}

	/**
	 * 当RFID已绑定设备时调用
	 */
	public void initmodify() {
		this.Latitude = eq.getLatitude();
		this.Longitude = eq.getLongitude();
		this.RfidNumber = eq.getRfidNumber();
		this.type = eq.getTypename();
		getTypePosition(type);
	}

	/**
	 * 初始化数据
	 * @param eq
	 */
	public void viewdate(OtherEquipmentPOVO eq) {
		textview3.setText(eq.getNumber());
		edit2.setText(eq.getAdds());
		edit3.setText(eq.getLocationadds());
		edit4.setText(eq.getDesc());
		textview4.setText("");
		textview1.setText("维度:" + eq.getLatitude());
		textview2.setText("经度:" + eq.getLongitude());
	}
   
	
	//保存更换设备信息
	public boolean save(){
		boolean b=false;
		ContentValues values=new ContentValues();
		values.put("ep_checktype", "更换");
		values.put("ep_checkdesc", edit5.getEditableText().toString()+",此设备被编号"+edit1.getEditableText().toString()+"更换");
		values.put("ep_checkdate", DateUtil.getBeforeDay(0));
		EquipementDao dao=new EquipementDao(this);
		dao.modify(id, DbTableName.EQUIPEMENT, values);
		OtherEquipmentPOVO e=new OtherEquipmentPOVO();
		e.setNumber(edit1.getEditableText().toString());
		e.setAdds(edit2.getEditableText().toString());
		e.setDesc(edit3.getEditableText().toString()+",替换设备"+textview3.getText().toString());
		e.setLocationadds(edit4.getEditableText().toString());		
		e.setTypename(type);
		e.setTypeid(typeid);
		e.setList(imagepath);
		e.setLongitude(Longitude);
		e.setLatitude(Latitude);
		e.setRfidNumber(RfidNumber);
		String str=dao.insertEquipement(e);
		if(str.equals("0")){
			b=false;
		}else{
			b=true;
		}
		dao.close();
		return b;
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		menu.add(0, ITEM0 + 1, 0, "拍照");
		//menu.add(0, ITEM0 + 2, 0, "定位方式");
		menu.add(0, ITEM0 + 3, 0, "读卡协议");
		menu.add(0, ITEM0 + 4, 0, "读卡方式");
		menu.findItem(ITEM0 + 1);

		return true;
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		Dialog dialog = null;
		switch (id) {

		case DIALOG:
			Builder builder1 = new android.app.AlertDialog.Builder(this);
			// 设置对话框的图标
			builder1.setIcon(R.drawable.buttondraw);
			builder1.setTitle("确定更换此设备？");
			builder1.setPositiveButton("确定",
					new android.content.DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							if (typeid.equals("0")) {
								Toast.makeText(EquipementReplaceActivity.this,
										"你还没选择类型！", Toast.LENGTH_LONG).show();
								return;
							}
							boolean b = save();
							if (b) {
								Toast.makeText(EquipementReplaceActivity.this,
										"添加成功", Toast.LENGTH_SHORT).show();
							} else {
								Toast.makeText(EquipementReplaceActivity.this,
										"添加失败", Toast.LENGTH_SHORT).show();
							}

						}
					});
			builder1.setNeutralButton("取消",
					new android.content.DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							finish();

						}
					});
			// 创建一个单选按钮对话框
			dialog = builder1.create();
			break;

		case DIALOG + 1:
			if (locationtype.equals("gps")) {
				date = new String[] { "gps", "network" };
			} else {
				date = new String[] { "network", "gps" };
			}
			AlertDialog.Builder builder = new android.app.AlertDialog.Builder(
					this);
			// 设置对话框的图标
			builder.setIcon(R.drawable.buttondraw);
			// 设置对话框的标题
			builder.setTitle("选择定位方式");

			builder.setSingleChoiceItems(date, 0,
					new android.content.DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							locationtype = date[which];
						}
					});

			// 添加一个确定按钮
			builder.setPositiveButton(" 确 定 ",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							initlocation();
						}
					});
			// 创建一个单选按钮对话框
			dialog = builder.create();
			break;
		case DIALOG + 2:
			builder = new android.app.AlertDialog.Builder(this);
			// 设置对话框的图标
			builder.setIcon(R.drawable.buttondraw);
			// 设置对话框的标题
			builder.setTitle("单选按钮对话框");
			// 0: 默认第一个单选按钮被选中

			builder.setSingleChoiceItems(R.array.hobby, 0,
					new android.content.DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							xieyi = getResources()
									.getStringArray(R.array.hobby)[which];

						}
					});

			// 添加一个确定按钮
			builder.setPositiveButton(" 确 定 ",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							if (xieyi.equals("15693")) {
								time = System.currentTimeMillis();
								initRFID(2);
							} else if (xieyi.equals("14443")) {
								time = System.currentTimeMillis();
								initRFID(1);
							}
						}
					});
			// 创建一个单选按钮对话框
			dialog = builder.create();
			break;
		case DIALOG + 3:
			if (readtype.equals("终端读卡")) {
				readdate = new String[] { "终端读卡", "蓝牙读卡" };
			} else {
				readdate = new String[] { "蓝牙读卡", "终端读卡" };
			}

			builder = new android.app.AlertDialog.Builder(this);
			// 设置对话框的图标
			builder.setIcon(R.drawable.buttondraw);
			// 设置对话框的标题
			builder.setTitle("读卡方式选择");
			// 0: 默认第一个单选按钮被选中

			builder.setSingleChoiceItems(readdate, 0,
					new android.content.DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							readtype = readdate[which];

						}
					});

			// 添加一个确定按钮
			builder.setPositiveButton(" 确 定 ",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							time = System.currentTimeMillis();
							bluehelp.start();
						}
					});
			// 创建一个单选按钮对话框
			dialog = builder.create();
			break;
		}

		return dialog;
	}

	/**
	 * 读卡消息
	 */
	public Handler MyHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			if (msg.what == 1) {
				isStop = false;
				if(readtype.equals("终端读卡")){
					pd.dismiss();
				}else{
					bluehelp.close();
				}

				TipHelper.Vibrate(EquipementReplaceActivity.this, 1000);
				textview4.setText(msg.obj.toString());

				RfidNumber = msg.obj.toString();
				EquipementDao dao = new EquipementDao(
						EquipementReplaceActivity.this);
				OtherEquipmentPOVO e = dao.queryOne(null, RfidNumber);
				dao.close();
				if (e != null) {
					Toast.makeText(EquipementReplaceActivity.this, "此RFID已绑定了设备",
							Toast.LENGTH_SHORT).show();
					eq = e;

					ismodify = true;
					initmodify();
					
					if (e.getIsadd().equals("新增")) {
                         edit1.setEnabled(true);
					}else{
						edit1.setEnabled(false);
					}
				}
			} else {
				isStop = false;
				Toast.makeText(EquipementReplaceActivity.this, "读卡超时", 1000).show();
				if(readtype.equals("终端读卡")){
					pd.dismiss();
				}else{
					bluehelp.close();
				}

			}
		}

	};

}
